const LogService = require('../services/logService');

/**
 * 用户操作日志中间件
 * @param {string} action 操作类型
 * @param {Function} [detailsExtractor] 详情提取函数
 */
const logMiddleware = (action, detailsExtractor = null) => {
  return async (req, res, next) => {
    const originalSend = res.send;
    
    // 重写 send 方法以捕获响应
    res.send = function(data) {
      res.send = originalSend;
      const result = res.send.call(this, data);
      
      // 异步记录日志，不阻塞响应
      (async () => {
        try {
          if (!req.user) return; // 未登录用户不记录

          const details = detailsExtractor ? await detailsExtractor(req, data) : {};
          
          await LogService.createLog({
            userId: req.user._id,
            action,
            ip: req.ip,
            userAgent: req.headers['user-agent'],
            details
          });
        } catch (error) {
          console.error('[日志中间件错误]', error);
        }
      })();

      return result;
    };

    next();
  };
};

module.exports = logMiddleware; 